package utilities.event;

import hibernate.HibernateInitializer;
import hibernate.hibernateInterface.ReservationInterface;
import hibernate.hibernateInterface.RoomSystemHibernateInterface;
import hibernate.roomSystem.ReservationForm;
import hibernate.roomSystem.Room;
import hibernate.roomSystem.RoomState;
import hibernate.roomSystem.RoomType;

import java.util.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
import org.zkoss.zk.ui.event.*;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zul.*;

public class ReservationController 
implements EventListener{
	public void onEvent(Event e){
		String action=(String)e.getPage().getAttribute("ACTION");
		if(action == null){
			try{new Messagebox().show("数据传输错误");}catch(Exception exp){}
			return;
		}else if(action.equals("FLUSH"))
			flush(e);
		else if(action.equals("ADD"))
			add(e);
		else if(action.equals("DEL"))
			del(e);
	}
	
	private String sizeParse(String size){
		if(size.equals("单人间"))
			return "SINGLE";
		if(size.equals("双人间"))
			return "DOUBLE";
		if(size.equals("三人间"))
			return "TRIPLE";
		if(size.equals("四人间"))
			return "QUAD";
		if(size.equals("套间"))
			return "SUITE";
		if(size.equals("总统套房"))
			return "TSU";
			return "STANDARD";
	}
	
	private static final HashSet stateSet=new HashSet();
	static{
		stateSet.add(RoomState.ConcreteType.getType("EMPTY"));
	}
	
	private String parseDocType(String str){
		if(str.equals("身份证"))
			return "ID_CARD";
		if(str.equals("军人证"))
			return "MILITANT_CARD";
			return "STUDENT_CARD";
	}
	
	private void add(Event e){
		Date timeIn=(Date)e.getPage().getAttribute("TIMEIN");
		Date timeOut=(Date)e.getPage().getAttribute("TIMEOUT");
		String type=sizeParse(e.getPage().getAttribute("ROOMTYPE").toString());
		Integer nr=(Integer)e.getPage().getAttribute("ROOMNR");
		String note=e.getPage().getAttribute("NOTE").toString();
		String name=e.getPage().getAttribute("NAME").toString();
		String tel=e.getPage().getAttribute("TEL") == null ? "" : e.getPage().getAttribute("TEL").toString();
		String docType=parseDocType(e.getPage().getAttribute("DOCTYPE").toString());
		String docNumber=e.getPage().getAttribute("DOCNUMBER").toString();
		Boolean sex=e.getPage().getAttribute("SEX").toString().equals("是");
		Boolean partTime=(Boolean)e.getPage().getAttribute("PART_TIME");
		
		Session session=null;
		try{
			
			session=HibernateInitializer.getSession();
			Transaction trans=session.beginTransaction();
			
			ReservationForm newForm=null;
			try{
				newForm=ReservationInterface.getReservationByDocNumber(docNumber, session);
			}catch(Exception exp){}
			if(newForm != null)
				try{new Messagebox().show("同样证件号的记录存在,系统自动覆盖该记录");}catch(Exception msgExp){}
			else newForm=new ReservationForm();
			
			newForm.setTimeAcommodation(timeIn);
			newForm.setTimeLeaving(timeOut);
			newForm.setTimeCreate(new Date());
			newForm.setRoomType(new RoomType());
			newForm.getRoomType().setSizeAndFacilities(type);
			newForm.setNumber(nr);
			newForm.setNote(note);
			newForm.setFirstName(name);
			newForm.setTelNumber1(tel);
			newForm.setDocType(docType);
			newForm.setDocNumber(docNumber);
			newForm.setSex(sex);
			newForm.setPartTime(partTime);
			
			Set roomSet=newForm.getReservedRooms();
			int i=roomSet.size();
			try{
				List rooms=RoomSystemHibernateInterface.getRoomsByState(stateSet,session);
				Iterator itr=rooms.iterator();
				while(itr.hasNext() && i < newForm.getNumber()){
					Room tempR=((Room)((Object[])itr.next())[0]);
					roomSet.add(tempR);
					i++;
				}
			}catch(Exception exp2){}
			newForm.setReservedRooms(roomSet);
				
			session.save(newForm);
			
			trans.commit();
			session.close();
			
		}catch(Exception exp){
			exp.printStackTrace();
			try{new Messagebox().show("数据添加失败");}catch(Exception msgExp){}
		}finally{
			if(session != null && session.isOpen())
				session.close();
			flush(e);
		}
	}
	
	private String parse(String docType){
		if(docType.equals("ID_CARD"))
			return "身份证";
		if(docType.equals("STUDENT_CARD"))
			return "学生证";
		if(docType.equals("MILITANT_CARD"))
			return "军人证";
		return "无";
	}
	
	private String parseSize(String size){
		if(size.equals("SINGLE"))
			return "单人间";
		if(size.equals("DOUBLE"))
			return "双人间";
		if(size.equals("TRIPLE"))
			return "三人间";
		if(size.equals("QUAD"))
			return "四人间";
		if(size.equals("SUITE"))
			return "套间";
		if(size.equals("TSU"))
			return "总统套房";
			return "标准间";
	}
	
	private void flush(Event e){
		Session session=null;
		try{
			
			session=HibernateInitializer.getSession();
			Transaction trans=session.beginTransaction();
			
			List ret=new LinkedList();
			List raw=ReservationInterface.getAllReservations(session);
			
			Iterator itr=raw.iterator();
			while(itr.hasNext()){
				ReservationForm form=(ReservationForm)itr.next();
				List newCol=new LinkedList();
				ret.add(newCol);
				newCol.add(form.getId());
				newCol.add(form.getFirstName());
				newCol.add(form.getSex() ? "男" : "女");
				newCol.add(parse(form.getDocType().toString()));
				newCol.add(form.getDocNumber() == null ? "无" : form.getDocNumber());
				newCol.add(form.getConcreteTelNumber1() == null ? "无" : form.getConcreteTelNumber1().getNumber());
				newCol.add(form.getTimeAcommodation() == null ? "无" : form.getTimeAcommodation());
				newCol.add(form.getTimeLeaving() == null ? "无" : form.getTimeLeaving());
				newCol.add(parseSize(form.getRoom().getSizeAndFacilities().toString()));
				newCol.add(form.getNumber());
				newCol.add(form.getPartTime() ? "是" : "否");
				StringBuffer buf=new StringBuffer();
				
				int num=0;
				if(form.getReservedRooms() == null){
					newCol.add("无房间信息");
					num=0;
				}else{
					num=0;
					Iterator itr2=form.getReservedRooms().iterator();
					while(itr2.hasNext()){
						Room r=(Room)itr2.next();
						buf.append(r.getRoomNumber());
						buf.append(",");
						num++;
					}
					newCol.add( buf.length() > 0 ? buf.substring(0,buf.length()-1) : "");
				}
				if(form.getTimeAcommodation() == null || form.getTimeAcommodation().before(new Date()))
					newCol.add(2);
				else if(num >= form.getNumber())
					newCol.add(0);
				else newCol.add(1);
			}
			
			trans.commit();
			session.close();
			
			e.getPage().setAttribute("COLDATA",ret);
			
		}catch(Exception exp){
			try{new Messagebox().show("刷新失败");}catch(Exception msgExp){}
			e.getPage().setAttribute("COLDATA",new LinkedList());
		}finally{
			if(session != null && session.isOpen())
				session.close();
		}
	}
	
	private void del(Event e){
		Long id=new Long(e.getPage().getAttribute("ID").toString());
		
		Session session=null;
		try{
			
			session=HibernateInitializer.getSession();
			Transaction trans=session.beginTransaction();
			
			ReservationForm tempForm=ReservationInterface.getReservationByID(id, session);
			
			if(tempForm.getTimeAcommodation().after(new Date())){	
				Set roomSet=tempForm.getReservedRooms();
				Iterator itr=roomSet.iterator();
				while(itr.hasNext()){
					Room r=(Room)itr.next();
					if(r.getRoomState() != null && 
					   r.getRoomState().getStates() != null && 
					   r.getRoomState().getStates().indexOf("RESERVED") >= 0){
						r.getRoomState().setStates("EMPTY");
						session.update(r.getRoomState());
					}
				}
			}
			
			session.delete(tempForm);
			
			trans.commit();
			session.close();
			
		}catch(Exception exp){
			exp.printStackTrace();
			try{new Messagebox().show("数据删除失败");}catch(Exception msgExp){}
		}finally{
			if(session != null && session.isOpen())
				session.close();
			flush(e);
		}
	}
}
